package com.huchengrui.guesssong2

import android.content.Context
import android.graphics.BitmapFactory
import android.widget.ImageView
import kotlinx.coroutines.*
import java.io.FileOutputStream
import java.net.HttpURLConnection
import java.net.URL

object SetPicture {
     fun setPicture(url: URL,context: Context,imageView: ImageView) {
        val scope= CoroutineScope(Job())
        scope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val connection = url.openConnection() as HttpURLConnection
                connection.readTimeout = 10000
                connection.connectTimeout = 10000
                connection.inputStream.use {inputStream->
                    FileOutputStream("${context.externalCacheDir!!.absolutePath}/background.jpg").use {
                        inputStream.buffered().copyTo(it.buffered())
                    }
                }
            }
            imageView.setImageBitmap(BitmapFactory.decodeFile("${context.externalCacheDir!!.absolutePath}/background.jpg"))
        }
    }
}